package ThreadDemo.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class Account {

    //定义锁对象,可重入锁
    private final ReentrantLock lock = new ReentrantLock();
    private String accountNo;
    private double balance;
    public Account() {}

    public Account(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public void draw(double drawAmount) {
        lock.lock();
        try {
            if (balance >= drawAmount) {
                System.out.println(Thread.currentThread().getName() + "取钱成功，吐出钞票：" + drawAmount);
                balance -= drawAmount;
                System.out.println("余额为 " + balance);
            } else {
                System.out.println(Thread.currentThread().getName() + "取钱失败，余额不足！");
            }
        } finally {
            //修改完毕，释放锁
            lock.unlock();
        }
    }
    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }


    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj != null && obj.getClass() == ThreadDemo.ThreadSecure.Account.class) {
            ThreadDemo.ThreadSecure.Account target = (ThreadDemo.ThreadSecure.Account)obj;
            return target.getAccountNo().equals(accountNo);
        }
        return false;
    }
}
